<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Action\Workbench;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkContact\Contract\WorkContactTagContract;
use MoChat\App\WorkContact\Contract\WorkContactTagPivotContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 一键拉群筛选客户.
 * @Controller
 */
class FilterContact extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployeeService;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactContract;

    /**
     * @Inject
     * @var WorkContactTagPivotContract
     */
    protected $workContactTagPivotService;

    /**
     * @Inject
     * @var WorkContactTagContract
     */
    protected $workContactTagContract;

    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/workContact/filterContact", methods="GET")
     * @return array 返回数组
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $corpId = $user['corpId'];
        $employeeId = $user['id'];

        // 参数验证
        $this->validated($this->request->all());

        // 接收参数
        $params = [
            'tags' => $this->request->input('tags'),
            'startTime' => $this->request->input('startTime', ''),
            'endTime' => $this->request->input('endTime', ''),
            'addWay' => $this->request->input('addWay', ''),
            'gender' => $this->request->input('gender', ''),
        ];
        $data = [
            'total' => 0,
            'list' => [],
        ];
        // 查询员工所有客户-添加时间
        $search = [
            'corpId' => $corpId,
            'employeeIds' => [$employeeId],
            'startTime' => $params['startTime'],
            'endTime' => $params['endTime'],
            'addWay' => $params['addWay'],
            'status' => 1,
        ];
        $contacts = $this->workContactEmployeeService->getWorkContactEmployeesBySearch($search, ['contact_id', 'create_time']);
        if (empty($contacts)) {
            return $data;
        }
        $contactIds = array_unique(array_column($contacts, 'contactId'));
        // 查询已打标签客户
        if (! empty($params['tags'])) {
            $contactsTag = $this->workContactTagPivotService->getWorkContactTagPivotsByContactIdsEmployeeIdsTagIds($contactIds, [$employeeId], $params['tags'], 1, ['contact_id']);
            if (empty($contactsTag)) {
                return $data;
            }
            $contactIds = array_unique(array_column($contactsTag, 'contactId'));
        }

        // 查询客户信息
        if ($params['gender'] === '' || $params['gender'] === null) {
            $list = $this->workContactContract->getWorkContactsById($contactIds, ['id', 'name', 'avatar', 'wx_external_userid']);
        } else {
            $list = $this->workContactContract->getWorkContactsByIdsGender($contactIds, (int) $params['gender'], ['id', 'name', 'avatar', 'wx_external_userid']);
        }

        $contacts = array_column($contacts, null, 'contactId');
        foreach ($list as &$item) {
            $item['avatar'] = file_full_url($item['avatar']);
            $item['createTime'] = $contacts[$item['id']] ? $contacts[$item['id']]['createTime'] : '';
            $item['tags'] = $this->getContactTags($item['id']);
        }
        unset($item);
        return ['count' => count($list), 'list' => $list];
    }

    private function getContactTags($contactId): array
    {
        $contactTags = $this->workContactTagPivotService->getWorkContactTagPivotsByContactId($contactId, ['contact_tag_id']);
        if (empty($contactTags)) {
            return [];
        }
        $tagIds = array_unique(array_column($contactTags, 'contactTagId'));
        $tags = $this->workContactTagContract->getWorkContactTagsById($tagIds, ['name']);
        return empty($tags) ? [] : array_column($tags, 'name');
    }
}
